package com.wctj.api.security.component;

import cn.hutool.core.util.URLUtil;
import com.wctj.api.base.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 动态权限数据源，用于获取动态权限规则
 * @author carol
 */
@Slf4j
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        if (configAttributeMap == null) {
            this.loadDataSource();
        }
        List<ConfigAttribute>  configAttributes = new ArrayList<>();
        //
        String url = ((FilterInvocation) o).getRequestUrl();
        String path = URLUtil.getPath(url);
        PathMatcher pathMatcher = new AntPathMatcher();
        //获取访问该路径所需资源
        // 使用 entrySet 迭代器遍历 map
        for (Map.Entry<String, ConfigAttribute> entry : configAttributeMap.entrySet()) {
            if (pathMatcher.match(entry.getKey(), path)) {
                configAttributes.add(entry.getValue());
            }
        }

//        //TODO,暂时放开任何路径都能访问 未设置操作请求权限，返回空集合,防止数据库中没有数据，不能进行权限拦截
//        if(CollectionUtils.isEmpty(configAttributes)){
//            ConfigAttribute configAttribute = new SecurityConfig("DEFAULT_NO_USER");
//            configAttributes.add(configAttribute);
//        }
        log.info("动态权限规则,获取当前访问的路径:{},{},该路径所需资源:{}",url,path, JsonUtils.toJson(configAttributes));
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {

//        return configAttributeMap.values();
        return new ArrayList<>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
//        return true;
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
